package cn.edu.lingnan.controller;


import cn.edu.lingnan.Interceptor.WebInterceptor;
import cn.edu.lingnan.common.Constants;
import cn.edu.lingnan.common.Result;
import cn.edu.lingnan.entity.Users;
import cn.edu.lingnan.entity.UsersAdmin;
import cn.edu.lingnan.entity.UsersStu;
import cn.edu.lingnan.entity.dto.InfoDto;
import cn.edu.lingnan.entity.dto.PasswordDto;
import cn.edu.lingnan.entity.dto.SelectDto;
import cn.edu.lingnan.entity.dto.UserDTO;
import cn.edu.lingnan.mapper.AdminUserMapper;
import cn.edu.lingnan.service.IUserService;
import cn.edu.lingnan.service.IUsersStuService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("/Users")

public class UserController {
    Random r = new Random();
    @Autowired
    private IUsersStuService iUsersStuService;

    @Autowired
    private IUserService userService;


    @Autowired
    private AdminUserMapper adminUserMapper;


    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        String usersPassword = userDTO.getUsersPassword();
        //下面代码是判断密码是否为空，并且判断是否又空格组成
        if (StrUtil.isBlank(usersPassword)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        UserDTO dto = userService.login(userDTO);

        String token = generateToken();//登录成功后
        dto.setToken(token);//把这个token装入到dto数据对象中
        userService.UpdateToken(dto);
        Integer temp = 0;
        if (dto.getUsersRole().equals("管理员")) {
            LambdaQueryWrapper<Users> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
            adminLambdaQueryWrapper.eq(Users::getUsersId, dto.getUsersId());
            Users one = userService.getOne(adminLambdaQueryWrapper);
            temp = one.getPermissionLevel();
            dto.setLevel(temp);
        }

        return Result.success(dto);
    }

//    @PostMapping("/register")
//    public Result register(@RequestBody UserDTO userDTO) {
//        String usersPassword = userDTO.getUsersPassword();
//        if (StrUtil.isBlank(usersPassword)) {
//            return Result.error(Constants.CODE_400, "参数错误");
//        }
//        /*UserDTO dto = userService.register(userDTO);*/
//        return Result.success(userService.register(userDTO));
//    }

    @GetMapping
    public Result findAll() {
        return Result.success(iUsersStuService.list());
    }


    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String usersStuName,
                           @RequestParam(defaultValue = "") String usersStuId) {
        QueryWrapper<UsersStu> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(usersStuName)) {
            queryWrapper.like("users_stu_name", usersStuName);
        }
        if (!"".equals(usersStuId)) {
            queryWrapper.like("users_stu_id", usersStuId);
        }
        return Result.success(iUsersStuService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    //编辑的保存
    @PostMapping("/editorSave")
    public Result EditorSave(@RequestBody SelectDto selectDto, @RequestHeader("Authorization") String token) {
        Users userByToken = userService.getUserByToken(token);
        boolean rs = userService.editorSave(selectDto, userByToken);

        if (rs) {
            return Result.success("修改成功");

        }
        return Result.error();
    }


    @GetMapping("/getAll")
    public SelectDto getAll() {
        Users user = WebInterceptor.getUsers();
        SelectDto usersDto = userService.getAll(user);
        System.out.println(usersDto);
        return usersDto;
    }

    @GetMapping("/getInfo")
    public InfoDto getInfo(@RequestParam("id") String id) {
        System.out.println(id);
        BigInteger bigInteger = new BigInteger(id);
        return userService.getInfo(bigInteger);
    }

    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody PasswordDto passwordDto) {
        boolean rs = userService.updatePassword(passwordDto);
        if (rs) {
            return Result.success();
        }
        return Result.error(Constants.CODE_400, "原密码错误！");
    }

    /**
     * 用户信息管理分页查询接口
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/admininfo/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        queryWrapper.ne("permission_level", 1);
        queryWrapper.eq("users_role", "管理员");
        Page<Users> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);


        return Result.success(page);

    }

    @PostMapping("/addmember")
    public Result addmember(@RequestBody Users users) {
        users.setId(userService.count() + 1);
        users.setUsersRole("管理员");

        userService.save(users);
        return Result.success();
    }


    // TODO: 2023/4/14 此方法建立了唯一标识
    private String generateToken() {
        String uuid = UUID.randomUUID().toString();//生成一个唯一token
        for (int i = 0; i < 5; i++) {
            Integer number = r.nextInt(10);
            uuid = uuid + number;
        }
        String token = uuid;


        return token;
    }


}

